﻿namespace S7.Net
{
    using System;
    using System.Net.Sockets;

    internal class TPKT
    {
        public byte[] Data;
        public int Length;
        public byte Reserved1;
        public byte Version;

        public static TPKT Read(Socket socket)
        {
            byte[] buffer = new byte[4];
            socket.Receive(buffer, 4, SocketFlags.None);
            TPKT tpkt1 = new TPKT {
                Version = buffer[0],
                Reserved1 = buffer[1],
                Length = (buffer[2] * 0x100) + buffer[3]
            };
            TPKT tpkt = tpkt1;
            if (tpkt.Length > 0)
            {
                tpkt.Data = new byte[tpkt.Length - 4];
                socket.Receive(tpkt.Data, tpkt.Length - 4, SocketFlags.None);
            }
            return tpkt;
        }

        public override string ToString()
        {
            return string.Format("Version: {0} Length: {1} Data: {2}", this.Version, this.Length, BitConverter.ToString(this.Data));
        }
    }
}

